package com.zhang.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.common.dto.PageSearchDTO;
import com.zhang.system.mapper.ConfigMapper;
import com.zhang.system.entity.Config;
import com.zhang.system.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 创世神
 * @since 2024-09-29 11:14:23
 */
@Service
@Slf4j
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService {

    @Autowired
    private ConfigMapper configMapper;

    @Override
    public Page<Config> findList(PageSearchDTO params) {
        LambdaQueryWrapper<Config> query = Wrappers.lambdaQuery(Config.class);
        if (!StrUtil.isEmpty(params.getSearchValue())) {
            query.or().eq(Config::getConfigKey, params.getSearchValue())
                    .or().eq(Config::getName, params.getSearchValue())
                    .or().eq(Config::getId, params.getSearchValue());
        }
        return configMapper.selectPage(new Page<Config>(params.getPageNum(), params.getPageSize()), query);
    }

    @Override
    public Config findById(Long id) {
        return configMapper.selectById(id);
    }

    @Override
    public boolean insert(Config config) {
//        TODO 考虑改成用户名
        config.setCreatBy(StpUtil.getLoginIdAsString());
        config.setCreatTime(LocalDateTime.now());
        return save(config);
    }

    @Override
    public boolean update(Config config) {
        return updateById(config);
    }

    @Override
    public int delete(Long id) {
        return configMapper.deleteById(id);
    }

    @Override
    public Config getConfigByKey(String key) {
        LambdaQueryWrapper<Config> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Config::getConfigKey,key);
        return getOne(wrapper);
    }

}
